#include "PatientInfoUi.h"
#include "ui_PatientInfoUi.h"
#include "WidgetHandler.h"
#include "BootSetting.h"
#include "MiscData.h"
#include "Database.h"
#include "MedicalInfo.h"
#include "HintDialog.h"
#include "Medio.h"
#include "ExportDialog.h"
#include "ExportWorker.h"
#include "FileUtility.h"
#include "LogoUtility.h"
#include "AuthorityDialog.h"
#include "Mcu.h"
#include "FilePaging.h"
#include <QDir>
#include <Mpp.h>
#include <QFileInfo>
PatientInfoUi::PatientInfoUi(QWidget *parent) :
    BaseWidget(parent),
    ui(new Ui::PatientInfoUi)
{
    ui->setupUi(this);
    LogoUtility::getInstance()->addLogoLabel(ui->logo);
    QObject::connect(HintDialog::getInstance(), &HintDialog::PatientInfoUi_HintDialog_Signal, this, &PatientInfoUi::PatientInfoUi_HintDialog_Slot);
    g_imageLabel.append(ui->image0);
    g_imageLabel.append(ui->image1);
    g_imageLabel.append(ui->image2);
    g_imageLabel.append(ui->image3);
    g_imageLabel.append(ui->image4);

    ui->image0->installEventFilter(this);
    ui->image1->installEventFilter(this);
    ui->image2->installEventFilter(this);
    ui->image3->installEventFilter(this);
    ui->image4->installEventFilter(this);

    g_videoLabel.append(ui->video0);
    g_videoLabel.append(ui->video1);
    g_videoLabel.append(ui->video2);
    g_videoLabel.append(ui->video3);
    g_videoLabel.append(ui->video4);

    ui->video0->installEventFilter(this);
    ui->video1->installEventFilter(this);
    ui->video2->installEventFilter(this);
    ui->video3->installEventFilter(this);
    ui->video4->installEventFilter(this);
    m_defaultPixmap = new QPixmap(":/image/image/defaultImage.png");
    m_defaultPixmap->scaled(ui->image0->width(),ui->image1->height());
    m_imageReader = new FilePaging("",5);
    m_videoReader = new FilePaging("",5);


    QObject::connect(AuthorityDialog::getInstance(), &AuthorityDialog::PatientInfoUi_Export_Signal,
                     this, &PatientInfoUi::PatientInfoUi_Export_Slot);

    QObject::connect(AuthorityDialog::getInstance(), &AuthorityDialog::PatientInfoUi_Delete_Signal,
                     this, &PatientInfoUi::PatientInfoUi_Delete_Slot);

    QObject::connect(AuthorityDialog::getInstance(), &AuthorityDialog::PatientInfoUi_Modify_Signal,
                     this, &PatientInfoUi::PatientInfoUi_Modify_Slot);

    ui->modifyPatient->hide();
}

PatientInfoUi::~PatientInfoUi()
{
    delete ui;
}

void PatientInfoUi::activate()
{
    m_allowOpreation = true;
    #ifdef arm
        Mpp::getInstance()->stopRealtimeImage();
    #endif
    /* 通过number查询 */
    int number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;
    PatientInfo* info = Database::getInstance()->queryPatient(number);
    if (info->number < 0) {
        qDebug()<<"PatientInfoUi, system error: no fine selected patient";
        return;
    }

    /* 更新ui */
    ui->info->setNumber(info->number);
    ui->info->setId(info->id);
    ui->info->setName(info->name);
    ui->info->setAge(info->age);
    ui->info->setBirthday(info->birthday);
    ui->info->setGender(info->gender);
    ui->info->setVisitTime(info->visitTime);
    ui->info->setPhone(info->phone);
    ui->info->setAddr(info->addr);
    m_imageReader->setFilePath(Medio::getInstance()->getCurrentPatientImagePath(1));
    m_videoReader->setFilePath(Medio::getInstance()->getCurrentPatientVideoPath(1));

    m_imageReader->getCurrPageFiles(m_images);
    updateImage();
    m_videoReader->getCurrPageFiles(m_videos);
    updateVideo();
}

void PatientInfoUi::inactivate()
{

}

void PatientInfoUi::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;

    default:
        break;
    }
}

bool PatientInfoUi::eventFilter(QObject *watched, QEvent *event)
{
    QString path;
    bool isPlayerImage = false;
    bool isPlayerVideo = false;

    QLabel *item =  dynamic_cast<QLabel*>(watched);
    int index;
    if(item&&event->type()==QEvent::MouseButtonPress){
         isPlayerImage =  (index = g_imageLabel.indexOf(item)) != -1;
         if(!isPlayerImage){
            isPlayerVideo = (index = g_videoLabel.indexOf(item)) != -1;
            if(isPlayerVideo && index<m_videos.length()){
                path = m_videos[index];
                QFileInfo temp(path);
                path = temp.dir().absolutePath();
                path +="/"+temp.baseName()+".mp4";
            }
         }else if(index<m_images.length()){
            path = m_images[index];
         }

    }

    if (isPlayerImage) {
        if(!m_allowOpreation) return false;
        isPlayerImage = false;
        if (path.isEmpty() || path.isNull())
            return false;
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentImagePath = path;
        WidgetHandler::getInstance()->displayWidget(PhotoPlayerUi_Id);
    }

    if (isPlayerVideo) {
        if(!m_allowOpreation) return false;
        isPlayerVideo = false;
        if (path.isEmpty() || path.isNull())
            return false;
        RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentMp4Path = path;
        WidgetHandler::getInstance()->displayWidget(VideoPlayerUi_Id);
    }

    return false;
}



void PatientInfoUi::updateImage(){
    for(auto &item:g_imageLabel){
        item->setPixmap(QPixmap(""));
    }
    int index = 0;
    ui->imageInfo->setText(tr("照片")+
                           QString("%1/%2")
                           .arg(m_imageReader->getCurrPageIndex()+(m_imageReader->pages()?1:0))
                           .arg(m_imageReader->pages()));
    for(auto &item:m_images){
        g_imageLabel[index]->setPixmap(QPixmap(item).scaled(g_imageLabel[index]->size()));
        ++index;
    }
}

void PatientInfoUi::updateVideo(){
    for(auto &item:g_videoLabel){
        item->setPixmap(QPixmap(""));
    }
    int index = 0;
    ui->videoInfo->setText(tr("视频")+
                           QString("%1/%2")
                           .arg(m_videoReader->getCurrPageIndex()+(m_videoReader->pages()?1:0))
                           .arg(m_videoReader->pages()));
    for(auto &item:m_videos){
        g_videoLabel[index]->setPixmap(QPixmap(item).scaled(g_videoLabel[index]->size()));

        ++index;
    }
}

void PatientInfoUi::on_gohome_clicked()
{
    if(!m_allowOpreation) return;
    Mcu::getInstance()->touchSoundBeepMessage();
    WidgetHandler::getInstance()->displayWidget(HomeUi_Id);
}

void PatientInfoUi::on_goback_clicked()
{
    if(!m_allowOpreation) return;
    Mcu::getInstance()->touchSoundBeepMessage();
    if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.patientInfoEntryType == 0) {
        WidgetHandler::getInstance()->displayWidget(HomeUi_Id);
    } else if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.patientInfoEntryType == 1) {
        WidgetHandler::getInstance()->displayWidget(QueryPatientUi_Id);
    }
}

void PatientInfoUi::on_modifyPatient_clicked()
{
    Mcu::getInstance()->touchSoundBeepMessage();

    int userId = RuntimeData::BootSetting::getInstance()->g_bootSettingInfo.currentUserId;

    if (userId < 0) {
        AuthorityDialog::getInstance()->setParent(this);
        AuthorityDialog::getInstance()->setAuthorityType(AuthorityType_PatientInfoUi_Modify);
        AuthorityDialog::getInstance()->exec();
        return;
    } else {
        PatientInfoUi_Modify_Slot();
    }
}

void PatientInfoUi::on_imageLeftPage_clicked()
{
    if(!m_allowOpreation) return;
    if(m_imageReader->prePage()){
       m_imageReader->getCurrPageFiles(m_images);
       updateImage();
    }

    Mcu::getInstance()->touchSoundBeepMessage();
}

void PatientInfoUi::on_imageRightPage_clicked()
{
    if(!m_allowOpreation) return;
    if(m_imageReader->nextPage()){
       m_imageReader->getCurrPageFiles(m_images);
       updateImage();
    }

    Mcu::getInstance()->touchSoundBeepMessage();
}

void PatientInfoUi::on_videoLeftPage_clicked()
{
    if(!m_allowOpreation) return;
    if(m_videoReader->prePage()){
       m_videoReader->getCurrPageFiles(m_videos);
       updateVideo();
    }
    Mcu::getInstance()->touchSoundBeepMessage();
}

void PatientInfoUi::on_videoRightPage_clicked()
{
    if(!m_allowOpreation) return;
    if(m_videoReader->nextPage()){
       m_videoReader->getCurrPageFiles(m_videos);
       updateVideo();
    }
    Mcu::getInstance()->touchSoundBeepMessage();
}

void PatientInfoUi::on_applyPatient_clicked()
{
    Mcu::getInstance()->touchSoundBeepMessage();
    RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;
    WidgetHandler::getInstance()->displayWidget(HomeUi_Id);
}

void PatientInfoUi::on_deletePatient_clicked()
{
    Mcu::getInstance()->touchSoundBeepMessage();

    int userId = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;

    if (userId < 0) {
        AuthorityDialog::getInstance()->setParent(this);
        AuthorityDialog::getInstance()->setAuthorityType(AuthorityType_PatientInfoUi_Delete);
        AuthorityDialog::getInstance()->exec();
        return;
    } else {
        PatientInfoUi_Delete_Slot();
    }
}

void PatientInfoUi::on_exportPatient_clicked()
{
    Mcu::getInstance()->touchSoundBeepMessage();

    int userId = RuntimeData::BootSetting::getInstance()->g_bootSettingInfo.currentUserId;

    if (userId < 0) {
        AuthorityDialog::getInstance()->setParent(this);
        AuthorityDialog::getInstance()->setAuthorityType(AuthorityType_PatientInfoUi_Export);
        AuthorityDialog::getInstance()->exec();
        return;
    } else {
       PatientInfoUi_Export_Slot();
    }
}

void PatientInfoUi::PatientInfoUi_HintDialog_Slot(int type)
{
    switch (type) {
    case PatientInfoUi_Delete:
        m_allowOpreation = false;
        qDebug()<<"ModifyPatientUi: PatientInfoUi_Delete";

        /* 删除患者 */
        int number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;
        /* 删除照片和视频 */
        Medio::getInstance()->deleteCurrentPatientMedio(number);

        if (Database::getInstance()->deletePatient(number) < 0) {
            qDebug()<<"delete failed";
            return;
        }
        if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber == number)
            RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber = -1;

        if (RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber == number)
            RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber = -1;


        int patientInfoEntryType = RuntimeData::MiscData::getInstance()->g_miscDataInfo.patientInfoEntryType;

        if (patientInfoEntryType == 0) {
            QTimer *timer = new QTimer(this);
            timer->setSingleShot(true);

            timer->start(1000);
            connect(timer, &QTimer::timeout, [timer](){
                WidgetHandler::getInstance()->displayWidget(HomeUi_Id);

                timer->deleteLater();
            });
        } else if (patientInfoEntryType == 1) {
            QTimer *timer = new QTimer(this);
            timer->setSingleShot(true);
            timer->start(1000);
            connect(timer, &QTimer::timeout, [timer](){
                WidgetHandler::getInstance()->displayWidget(QueryPatientUi_Id);
                timer->deleteLater();
            });
        }
        break;
    }
}

void PatientInfoUi::PatientInfoUi_Export_Slot()
{
    int number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;

    if (FileUtility::getInstance()->checkUsbDirExist("/run/media") < 0) {
        HintDialog::getInstance()->setInfo(tr("未找到外部存储设备!"), HintDialogType_Hint);
        HintDialog::getInstance()->exec();
        return;
    }
    ExportWorker::getInstance()->startWork(number);
    ExportDialog::getInstance()->exec();
}

void PatientInfoUi::PatientInfoUi_Delete_Slot() {
    HintDialog::getInstance()->setInfo(QString(tr("是否删除当前患者?")), PatientInfoUi_Delete);
    HintDialog::getInstance()->exec();
}

void PatientInfoUi::PatientInfoUi_Modify_Slot()
{
    WidgetHandler::getInstance()->displayWidget(ModifyPatientUi_Id);
}
